package com.skzh.framework.aspectj;

import java.util.Objects;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.skzh.common.annotation.DataSource;
import com.skzh.common.utils.StringUtils;
import com.skzh.framework.datasource.DynamicDataSourceContextHolder;

/**
 * 多数据源处理
 *
 * @author skzh
 *
 * 若依自带用于多数据源切换的切面类
 */
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.skzh.common.annotation.DataSource)"
            + "|| @within(com.skzh.common.annotation.DataSource)" )
    public void dsPointCut() {
        // 拦截所有带有 @DataSource 注解的方法和类
    }

    @Around("dsPointCut()" )
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 1. 获取 @DataSource 注解
        DataSource dataSource = getDataSource(point);
        
        // 2. 设置数据源类型到 ThreadLocal
        if (StringUtils.isNotNull(dataSource)) {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }
        
        try {
            // 3. 执行原方法（此时数据源已经切换）
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            // 4. 清除 ThreadLocal
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public DataSource getDataSource(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource;
        }

        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }
}
